﻿function Windows-CreateLocalUser
{
	PARAM
	(
		[String]$UserName=$(throw 'Parameter -UserName is missing!'),
		[String]$Password=$(throw 'Parameter -Password is missing!')
	)
	Trap
	{
		Write-Host "Error: $($_.Exception.GetType().FullName)" -ForegroundColor Red ; 
		Write-Host $_.Exception.Message; 
		Write-Host $_.Exception.StackTrack;
		break;
	}
	
	Write-Host "Creating $($UserName)";
	
	Invoke-Expression "& net user $($UserName) `"/add`" $($Password) `"/passwordchg:no`" `"/expires:never`" ";
}

function Windows-CreateLocalGroup
{
	PARAM
	(
		[String]$LocalGroupName=$(throw 'Parameter -GroupName is missing!')
	)
	Trap
	{
		Write-Host "Error: $($_.Exception.GetType().FullName)" -ForegroundColor Red ; 
		Write-Host $_.Exception.Message; 
		Write-Host $_.Exception.StackTrack;
		break;
	}
	
	Write-Host "Adding Localgroup $($LocalGroupName)";
	Invoke-Expression "& NET LOCALGROUP $($LocalGroupName) /add";

}

function Windows-RenameLocalUser
{
	PARAM
	(
		[String]$ComputerName=$(throw 'Parameter -ComputerName is missing!'),
		[String]$OldUserName=$(throw 'Parameter -OldUserName is missing!'),
		[String]$NewUserName=$(throw 'Parameter -NewUserName is missing!')
	)
	Trap
	{
		Write-Host "Error: $($_.Exception.GetType().FullName)" -ForegroundColor Red; 
		Write-Host $_.Exception.Message; 
		Write-Host $_.Exception.StackTrack;
		break;
	}
	$objUser=[adsi]("WinNT://" + $ComputerName + “/$($OldUserName), user”); 
	$objUser.psbase.rename($($NewUserName));
}

function Windows-GrantFullReadWriteAccessToFolder 
{

PARAM
	(
		[String]$Path=$(throw 'Parameter -Path is missing!'),
		[String]$UserName=$(throw 'Parameter -UserName is missing!')
	)
	Trap
	{
		Write-Host "Error: $($_.Exception.GetType().FullName)" -ForegroundColor Red ; 
		Write-Host $_.Exception.Message; 
		Write-Host $_.Exception.StackTrack;
		break;
	}
	
	$colRights = [System.Security.AccessControl.FileSystemRights]::FullControl;
	$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit;
	$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None;
	$objType =[System.Security.AccessControl.AccessControlType]::Allow;
	
	$Acl = Get-Acl "$path";
	$Ar = New-Object system.security.accesscontrol.filesystemaccessrule("$UserName", $colRights, $InheritanceFlag, $PropagationFlag, $objType);
	$Acl.SetAccessRule($Ar);
	Set-Acl $path $Acl; 	
}

function Windows-GrantFullReadWriteAccessToFile 
{

PARAM
	(
		[String]$Path=$(throw 'Parameter -Path is missing!'),
		[String]$UserName=$(throw 'Parameter -UserName is missing!')
	)
	Trap
	{
		Write-Host "Error: $($_.Exception.GetType().FullName)" -ForegroundColor Red ; 
		Write-Host $_.Exception.Message; 
		Write-Host $_.Exception.StackTrack;
		break;
	}
	
	$colRights = [System.Security.AccessControl.FileSystemRights]::FullControl;
	$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit;
	$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None;
	$objType =[System.Security.AccessControl.AccessControlType]::Allow;
	
	$Acl = Get-Acl "$path";
	$Ar = New-Object system.security.accesscontrol.filesystemaccessrule("$UserName", $colRights, $objType);
	$Acl.SetAccessRule($Ar);
	Set-Acl $path $Acl; 	
}

function Windows-CreateDirectory
{
	PARAM
	(
		[String]$DirectoryName=$(throw 'Parameter -DirectoryName is missing!'),
		[String]$Path=$(throw 'Parameter -DirectoryName is missing!')
	)
	Trap
	{
		Write-Host "Error: $($_.Exception.GetType().FullName)" -ForegroundColor Red ; 
		Write-Host $_.Exception.Message; 
		Write-Host $_.Exception.StackTrack;
		break;
	}
	$FullPath=Join-Path -Path $($Path) -ChildPath $($DirectoryName);
	
	if ( Test-Path -Path $FullPath)
	{
		Write-Host "Directory already exists";
		throw;
	}
	else
	{
		Invoke-Expression "& mkdir  $FullPath";
	}
}

function Windows-CreateShortCut
{
    PARAM
    (
        $Path = $(throw "Name parameter missing."),
        $TargetPath = $(throw "TargetPath parameter missing."),
        $Arguments = "",
        $WorkingDirectory = "",
        $Description = ""
    )
    
    $wshshell = New-Object -ComObject WScript.Shell;
    $link = $wshshell.CreateShortcut($Path);
    $link.TargetPath = $TargetPath;
    $link.Arguments = $Arguments;
    $link.WorkingDirectory = $WorkingDirectory;
    $link.Description = $Description;
    $link.Save();
}

function Windows-UpdateHostsFile
(
	[string]$IPAddress,
	[string]$Hostname
)
{
	[string]$hostsPath = "c:\windows\system32\drivers\etc\hosts";
	$lines = ( Get-Content -Path $hostsPath ) ;
	$uncommentedLines = $lines | where { ( $_.StartsWith("#") -ne $true ) };
	
	if( $uncommentedLines | where { $_ -match "$($IPAddress)" -and $_ -match "$($Hostname)" } )
	{
		return;
	}
	
	$lines += "$($IPAddress)`t$($Hostname)";
	
	Set-Content -Path $hostsPath -Value $lines;
}

function Windows-GetUserNameFromLogin
(
	[string]$LoginName
)
{
	 return $LoginName.Substring($LoginName.IndexOf("\") + 1)
}

function Windows-GetDomainFromLogin
(
	[string]$LoginName
)
{
	 return $LoginName.Substring(0,$LoginName.IndexOf("\")) 
}

<#
.Synopsis
	Add a domain user to a local windows group on any machine.
.Description
.Parameter $ComputerName,
.Example
	PS> Windows-AddUserToLocalGroup -ComputerName $ComputerName -Account 'YourAccount'
.Link
	about_functions
	about_functions_advanced
	about_functions_advanced_methods
	about_functions_advanced_parameters
 .Notes
	Uses WMI to talk to the local/remote machine. 	
#>
function Windows-AddUserToLocalGroup
{
	param(
	[Parameter(Position=0, ValueFromPipeline=$true)]$ComputerName = $Env:COMPUTERNAME,
	[Parameter(Position=1, Mandatory=$true)]$UserName,
	[Parameter(Position=2, Mandatory=$true)]$LocalGroupName
	)

	if($ComputerName -eq ".")
	{
		$ComputerName = (get-WmiObject win32_computersystem).Name;
	}    

	$ComputerName = $ComputerName.ToUpper();
	$Domain = $env:USERDNSDOMAIN;
	
	if( $UserName.Contains( "\" ) )
	{
		$Domain = Windows-GetDomainFromLogin -LoginName $UserName;
		$UserName = Windows-GetUserNameFromLogin -LoginName $UserName;
	}

	if($Domain)
	{
		if( ( Windows-IsUserInLocalGroup -ComputerName $ComputerName -UserName $UserName -LocalGroupName $LocalGroupName ) -eq $false )
		{
			Write-Host "Adding user $($Domain)\$($UserName) to $($ComputerName)\$($LocalGroupName).";
			$adsi = [ADSI]"WinNT://$($ComputerName)/$($LocalGroupName),group";
			$adsi.add("WinNT://$($Domain)/$($UserName),user");
		}
		else
		{
			Write-Host "User $($UserName) is already a member of $($ComputerName)\$($LocalGroupName)." -ForegroundColor Green;
		}
	}
	else
	{
		Write-Error "Not connected to a domain.";
	}
}


function Windows-IsUserInLocalGroup
{
	param(
	[Parameter(Position=0, ValueFromPipeline=$true)]$ComputerName = '.',
	[Parameter(Position=1, Mandatory=$true)]$UserName,
	[Parameter(Position=2, Mandatory=$true)]$LocalGroupName
	)

	if($ComputerName -eq ".")
	{
		$ComputerName = (get-WmiObject win32_computersystem).Name;
	}    

	$ComputerName = $ComputerName.ToUpper();
	$Domain = $env:USERDNSDOMAIN;

	if($Domain)
	{
		$group =[ADSI]"WinNT://./$($LocalGroupName)" 
		$members = @($group.psbase.Invoke("Members")) 
		$member = $members | where { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -ieq $UserName };

		return ( $member -ne $null )
	}
	else
	{
		Write-Error "Not connected to a domain.";
	}
}

function Add-NewEventLogSource
{
	param(
		[Parameter(Position=0, Mandatory=$true)]
		$NewSourceName = '.'
	)
	
   if(![System.Diagnostics.EventLog]::SourceExists($NewSourceName))
   {
   		Write-Host "Creating event log source $($NewSourceName)..." -ForegroundColor Green;
		
		[System.Diagnostics.EventLog]::CreateEventSource($NewSourceName,'Application')
   }
   else{
   		Write-Host "$($NewSourceName) already exists..." -ForegroundColor Yellow;
   }
}
